package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.EmployeeUpdPasswordDTO;
import com.sky.dto.mapper.EmpDTOMapper;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.mapper.EmployeeMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;

/**
 * @author luo20
 * @description 针对表【employee(员工信息)】的数据库操作Service实现
 * @createDate 2025-07-04 17:20:05
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee>
        implements EmployeeService{

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmpDTOMapper empDTOMapper;

    @Override
    @AutoFill(value = OperationType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    public Integer save(EmployeeDTO employeeDTO) {
        log.debug("当前线程的id: {}", Thread.currentThread().getId());
        // mapstruct对象属性自动映射
        Employee emp = empDTOMapper.toEmp(employeeDTO);
        // 设置账号的状态，默认正常状态 1 表示正常 0 表示锁定
        emp.setStatus(StatusConstant.ENABLE);
        // 设置密码，默认密码123456
        emp.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        // 设置当前记录的创建时间和修改时间
        // emp.setCreateTime(LocalDateTime.now());
        // emp.setUpdateTime(LocalDateTime.now());
        // 设置当前创建人ID和修改人ID
        // TODO 后期需要改为当前用户登录id
        // emp.setCreateUser(BaseContext.getCurrentId());
        // emp.setUpdateUser(BaseContext.getCurrentId());

        return employeeMapper.insertEmp(emp);
    }

    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //对前端传入的密明文码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public PageResult<Employee> EmpPage(EmployeePageQueryDTO employeePageQueryDTO) {
        //开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //查询员工列表
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.like(ObjectUtils.isNotEmpty(employeePageQueryDTO.getName()),Employee::getName, employeePageQueryDTO.getName());
        employeeLambdaQueryWrapper.orderByDesc(Employee::getCreateTime);
        List<Employee> employeeList = employeeMapper.selectList(employeeLambdaQueryWrapper);
        //封装分页结果
        Page<Employee> employeePage = (Page<Employee>) employeeList;
        return PageResult.<Employee>builder()
                .total(employeePage.getTotal())
                .records(employeePage.getResult()).build();
    }

    @Override
    public Integer updStatus(HashMap<String, Object> empMap) {
        Long id = ((Integer) empMap.get("id")).longValue();
        Integer status = (Integer) empMap.get("status");
        Employee employee = new Employee()
                .setId(id)
                .setStatus(status);
        return employeeMapper.updStatus(employee);
    }

    @Override
    @AutoFill(value = OperationType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public Integer update(EmployeeDTO employeeDTO) {
        //mapstruct对象属性自动映射
        Employee emp = empDTOMapper.toEmp(employeeDTO);
        // 设置当前记录的修改时间
        // emp.setUpdateTime(LocalDateTime.now());
        // 设置当前修改人ID
        // emp.setUpdateUser(BaseContext.getCurrentId());
        // 设置条件构造器
        LambdaUpdateWrapper<Employee> employeeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        employeeLambdaUpdateWrapper.eq(Employee::getId,emp.getId());
        employeeLambdaUpdateWrapper.set(Employee::getUsername,emp.getUsername());
        employeeLambdaUpdateWrapper.set(Employee::getName,emp.getName());
        employeeLambdaUpdateWrapper.set(Employee::getPhone,emp.getPhone());
        employeeLambdaUpdateWrapper.set(Employee::getIdNumber,emp.getIdNumber());
        employeeLambdaUpdateWrapper.set(ObjectUtils.isNotEmpty(emp.getSex()),Employee::getSex,emp.getSex());
        employeeLambdaUpdateWrapper.set(Employee::getUpdateTime,emp.getUpdateTime());
        employeeLambdaUpdateWrapper.set(Employee::getUpdateUser,emp.getUpdateUser());
        return employeeMapper.update(employeeLambdaUpdateWrapper);
    }

    @Override
    public void editPassword(EmployeeUpdPasswordDTO employeeUpdPasswordDTO) {
        String oldPassword = employeeUpdPasswordDTO.getOldPassword();
        String newPassword = employeeUpdPasswordDTO.getNewPassword();
        // 查询原账号密码,当前登录用户id
        Employee employee = employeeMapper.selectById(BaseContext.getCurrentId());
        // 对旧密码进行md5加密
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        // 判断原密码是否正确
        if (!oldPassword.equals(employee.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        // 对新密码进行md5加密
        newPassword = DigestUtils.md5DigestAsHex(employeeUpdPasswordDTO.getNewPassword().getBytes());
        // 存储到hashMap中
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("empId",employee.getId());
        hashMap.put("newPassword",newPassword);
        log.info("hashMap数据：{}",hashMap);
        // 修改密码
        Integer count = employeeMapper.editPassword(hashMap);
        if (count <= 0) {
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }

    }
}




